package cn.tedu.learn.tea.boot.config;

import cn.tedu.learn.tea.domain.common.exception.BusinessException;
import cn.tedu.learn.tea.domain.response.ResultVo;
import cn.tedu.learn.tea.domain.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 */
@RestControllerAdvice(basePackages = {"cn.tedu.learn.tea.adapter.controller"})
@Slf4j
public class GlobalControllerExceptionHandler {

    /**
     * 功能描述: controller层的BindException被捕获统一处理为1002, "参数原因"
     */
    @ExceptionHandler({BindException.class})
    public ResultVo bindExceptionHandler(BindException e) {
        // 从异常对象中拿到ObjectError对象
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return new ResultVo(StatusCode.VALIDATE_ERROR, objectError.getDefaultMessage());
    }

    /**
     * 功能描述: controller层的针对@RequestBody报出的异常拦截处理
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ResultVo methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        // 从异常对象中拿到ObjectError对象
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return new ResultVo(StatusCode.VALIDATE_ERROR, objectError.getDefaultMessage());
    }

    /**
     * 功能描述: controller层的APIException被捕获统一返回
     */
    @ExceptionHandler(BusinessException.class)
    public ResultVo apiExceptionHandler(BusinessException e) {
        log.error(e.getMessage(), e);
        return new ResultVo(e.getCode(), e.getMsg(), e.getMessage());
    }
}
